<?php

namespace Portal\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Portal\UserBundle\Entity\UserForgetPassword;


class ProfileController extends Controller
{
  public function indexAction()
  {

    // CHECK PLAIN PASSWORD 
    $session = $this->getRequest()->getSession();
    $tmpPlainPassword = null;
    if ($session->get('plainPassword')) {
      $tmpPlainPassword = $session->get('plainPassword');
      $session->remove('plainPassword');
    }


  return $this->render('PortalUserBundle:Profile:index.html.twig', array('tmpPlainPassword' => $tmpPlainPassword));
  }
  
  public function forgetPasswordAction()
  {
    return $this->render('PortalUserBundle:Forget:forget.html.twig', array('error' => ''));
  }
  
  public function forgetPasswordConfirmAction(Request $request)
  {
    if ($request->getMethod() != 'POST') {
      $this->get('session')->setFlash('error', 'Зөвшөөрөгдөөгүй хандалт!');
      return $this->redirect($this->generateUrl('logout'));
    }
    
    // GET POST VALUES
    $postValues = $request->request;
    
    $email = $postValues->get('email');
    $time = time();    
    $string = $email.'-'.$time;
    
    $hash = openssl_digest($string, 'sha512');
    
    $user = $this->getDoctrine()->getEntityManager()->getRepository('PortalUserBundle:User')->findBy(array('email'=>$email));
    
    if($user){
      $user = $user[0];
      $forgetPasswordObject = new UserForgetPassword();
      $forgetPasswordObject->setEmail($email);
      $forgetPasswordObject->setUserId($user->getId());
      $forgetPasswordObject->setToken($hash);
      $forgetPasswordObject->setIsActive(1);
      $forgetPasswordObject->setCreatedAt(date());

      $em = $this->getDoctrine()->getManager();
      $em->persist($forgetPasswordObject);
      $em->flush();
    
      echo 'y';
      die;
      
    }else{
      echo 'x';die;
    }
    
    
    
  }
  
}
